package com.topisv.tms.web;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.GoodsShelf;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.PipeStock;
import com.topisv.tms.entity.PipeStockDetail;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.Storage;
import com.topisv.tms.entity.StoragePartition;
import com.topisv.tms.entity.StoragePipe;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.GoodsShelfService;
import com.topisv.tms.service.PipeStockDetailService;
import com.topisv.tms.service.PipeStockService;
import com.topisv.tms.service.StoragePartitionService;
import com.topisv.tms.service.StoragePipeService;
import com.topisv.tms.service.StorageService;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 
 * @author Arthur
 */
@Controller
@RequestMapping(value = "/v2/storage")
public class StorageController extends BaseDataTableController{

	/*private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
	static {
		sortTypes.put("auto", "自动");
		sortTypes.put("name", "按照库区名称");
		sortTypes.put("type", "按照库区类型");
		sortTypes.put("areaGroup", "按照所属服务网点");
	}*/

	@Autowired
	private StorageService storageService;
	
	@Autowired
	private StoragePartitionService storagePartitionService;
	
	@Autowired
	private StoragePipeService storagePipeService;
	
	@Autowired
	private GoodsShelfService goodsShelfService;
	@Autowired
	private PipeStockService pipeStockService;
	
	@Autowired
	private PipeStockDetailService pipeStockDetailService;
	
	@Autowired
	private AreaGroupService areaGroupService;

	@RequestMapping(value = "v2_list")
	public String list() {
		return "storage/storageList";
	}

	@RequestMapping(value = "page")
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson);
			Page<Storage> page = storageService.getStorages(paramHolder);
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			
		}
	}
	
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		List<AreaGroup> areaGroups = storageService.getAllAreaGroups();
		model.addAttribute("areaGroups", areaGroups);
		model.addAttribute("storage", new Storage());
		model.addAttribute("action", "create");
		return "storage/storageForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid Storage storage, RedirectAttributes redirectAttributes) {
		Storage _storage = storageService.findByCode(storage.getCode());
		if(null != _storage)
		{
			redirectAttributes.addFlashAttribute("message", "创建库区失败：库区编码已存在");
			return "redirect:/v2/storage/v2_list";
		}
		AreaGroup areaGroup = areaGroupService.getAreaGroup(storage.getAreagroupId());
		storage.setAreaGroup(areaGroup);
		storageService.saveStorage(storage);
		redirectAttributes.addFlashAttribute("message", "创建库区成功");
		return "redirect:/v2/storage/v2_list";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		List<AreaGroup> areaGroups = storageService.getAllAreaGroups();
		Storage storage = storageService.getStorage(id);
		List<StoragePartition> sps = storagePartitionService.findBySPCode(storage.getCode());
		model.addAttribute("areaGroups", areaGroups);
		model.addAttribute("storage", storage);
		model.addAttribute("storagePartitions", sps);
		model.addAttribute("action", "update");
		return "storage/storageForm";
	}
	@RequestMapping(value = "partition/{id}", method = RequestMethod.GET)
	public String partition(@PathVariable("id") Long id, Model model) {
		StoragePartition sps = storagePartitionService.getStoragePartition(id);
		List<StoragePipe> pipes = storagePipeService.findBySPCode(sps.getPartition_code());
		List<GoodsShelf> goodsShelfs = goodsShelfService.getAllGoodsShelf();
		model.addAttribute("storagePartition", sps);
		model.addAttribute("storagePipes", pipes);
		model.addAttribute("goodsShelfs", goodsShelfs);
		model.addAttribute("action", "update");
		return "storage/storagePartitionForm";
	}
	@RequestMapping(value = "storagePartition/{partition_code}", method = RequestMethod.GET)
	public String storagePartition(@PathVariable("partition_code") String partition_code, Model model) {
		StoragePartition sps = storagePartitionService.findByCode(partition_code);
		List<StoragePipe> pipes = storagePipeService.findBySPCode(sps.getPartition_code());
		List<GoodsShelf> goodsShelfs = goodsShelfService.getAllGoodsShelf();
		model.addAttribute("storagePartition", sps);
		model.addAttribute("storagePipes", pipes);
		model.addAttribute("goodsShelfs", goodsShelfs);
		model.addAttribute("action", "update");
		return "storage/storagePartitionForm";
	}
	
	@RequestMapping(value = "storagePipe/{id}/{shelf_code}", method = RequestMethod.GET)
	public String storagePipe(@PathVariable("id") Long id,@PathVariable("shelf_code") String shelf_code, Model model,HttpServletRequest request) {
		StoragePipe storagePipe = storagePipeService.getStoragePipe(id);
		List<PipeStock> pipeStocks = pipeStockService.findByPipeCode(storagePipe.getPipe_code(), shelf_code);
		GoodsShelf goodsShelf = goodsShelfService.findByCode(storagePipe.getShelf_type());
		Map<String,PipeStock> map = new HashMap<String, PipeStock>();
		for(PipeStock ps : pipeStocks)
		{
			if("1".equals(ps.getStock_type()))
			{
				List<PipeStockDetail> detail = pipeStockDetailService.findByStockCode(ps.getStock_code());
				ps.setPipeStockDetailList(detail);
			}
			map.put(ps.getStock_code(), ps);
		}
		model.addAttribute("storagePipe", storagePipe);
		model.addAttribute("shelf_code", shelf_code);
		model.addAttribute("pipeStocks", map);
		request.setAttribute("goodsShelf", goodsShelf);
		return "storage/pipeStockForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("storage") Storage storage,RedirectAttributes redirectAttributes) {
		AreaGroup areaGroup = areaGroupService.getAreaGroup(storage.getAreagroupId());
		storage.setAreaGroup(areaGroup);
		storageService.saveStorage(storage);
		redirectAttributes.addFlashAttribute("message", "创建库区成功");
		return "redirect:/v2/storage/v2_list";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		storageService.deleteStorage(id);
		redirectAttributes.addFlashAttribute("message", "删除区域成功");
		return "redirect:/v2/storage/v2_list";
	}
	
	@RequestMapping(value = "addPartition")
	public void addPartition(@RequestParam(value = "storage_id") Long storage_id,
			@RequestParam(value = "partition_code") String partition_code,
			@RequestParam(value = "partition_name") String partition_name,
			@RequestParam(value = "partition_remark") String partition_remark,
			HttpServletResponse response) 
	{
		PrintWriter out = null;
		JSONObject json = null;
		json = new JSONObject();
		try
		{
			out = response.getWriter();
			Storage storage = storageService.getStorage(storage_id);
			StoragePartition sp = new StoragePartition();
			sp.setPartition_name(partition_name);
			sp.setPartition_code(storage.getCode()+partition_code);
			sp.setStorage_code(storage.getCode());
			sp.setPartition_remark(partition_remark);
			sp.setAreagroup_code(storage.getAreaGroup().getGroupCode());
			storagePartitionService.saveStoragePartition(sp);
			json.put("status", "1");
			out.print(json.toString());
		}
		catch(Exception e)
		{
			json.put("status", "0");
			out.print(json.toString());
		}
	}
	
	@RequestMapping(value = "stockDetail")
	public void stockDetail(@RequestParam(value = "stock_code") String stock_code,
			@RequestParam(value = "detail_num") int detail_num,
			HttpServletResponse response) 
	{
		PrintWriter out = null;
		JSONObject json = null;
		json = new JSONObject();
		try
		{
			out = response.getWriter();
			PipeStock pipeStock = pipeStockService.findByStockCode(stock_code);
			pipeStock.setStock_type("1");
			pipeStockService.savePipeStock(pipeStock);
			
			for(int i=1; i<=detail_num; i++)
			{
				PipeStockDetail psd = new PipeStockDetail();
				psd.setStock_code(stock_code);
				psd.setCustomer_code("");
				psd.setDetail_code(stock_code + i);
				psd.setDetail_name(i+"");
				psd.setIndex_num(i+"");
				psd.setStock_status("0");
				pipeStockDetailService.savePipeStockDetail(psd);
			}
			
			json.put("status", "1");
			out.print(json.toString());
		}
		catch(Exception e)
		{
			json.put("status", "0");
			out.print(json.toString());
		}
	}
	
	@RequestMapping(value = "addPipe")
	public void addPipe(@RequestParam(value = "storagePartition_id") Long storagePartition_id,
			@RequestParam(value = "shelf_num") int shelf_num,
			@RequestParam(value = "shelf_type") String shelf_type,
			HttpServletResponse response) 
	{
		PrintWriter out = null;
		JSONObject json = null;
		json = new JSONObject();
		try
		{
			out = response.getWriter();
			StoragePartition sp = storagePartitionService.getStoragePartition(storagePartition_id);
			GoodsShelf gs = goodsShelfService.findByCode(shelf_type);
			int rowsnum = gs.getRowsnum();
			int colsnum = gs.getColsnum();
			
			int pipenum = sp.getPipe_num() + 1;
			String pipe_code = "";
			if(pipenum < 10)
			{
				pipe_code = "0" + pipenum;
			}
			else if( pipenum >= 10 && pipenum < 100)
			{
				pipe_code = pipenum + "";
			}
			StoragePipe storagePipe = new StoragePipe();
			storagePipe.setPipe_code(sp.getPartition_code() + pipe_code);
			storagePipe.setPipe_name(pipe_code);
			storagePipe.setShelf_num(shelf_num+"");
			storagePipe.setShelf_type(gs.getShelf_code());
			storagePipe.setPipe_index(pipenum+"");
			storagePipe.setPartitionCode(sp.getPartition_code());
			storagePipeService.saveStoragePipe(storagePipe);
			for(int i=0; i<shelf_num; i++)
			{
				int num = i+1;
				/*String shelf_code = "";
				if( num < 10)
				{
					shelf_code = "00" + num;
				}
				else if( num >= 10 && num < 100)
				{
					shelf_code = "0" + num;
				}*/
				for(int rows=0; rows<rowsnum; rows++)
				{
					String row_code = "" + (rows+1);
					for(int cols=0; cols<colsnum; cols++)
					{
						String cols_code = "" + (cols+1);
						PipeStock pipeStock = new PipeStock();
						pipeStock.setPartition_code(sp.getPartition_code());
						pipeStock.setAreagroup_code(sp.getAreagroup_code());
						pipeStock.setCustomer_code("");
						pipeStock.setPartition_code(sp.getPartition_code());
						pipeStock.setStock_name(num + row_code + cols_code);
						pipeStock.setStock_code(storagePipe.getPipe_code()+ "-" + num + row_code + cols_code);
						pipeStock.setSku_id("");
						pipeStock.setPipe_code(storagePipe.getPipe_code());
						pipeStock.setStock_status("0");
						pipeStock.setStock_type("0");
						pipeStock.setStorage_code(sp.getStorage_code());
						pipeStock.setShelf_code(num+"");
						pipeStockService.savePipeStock(pipeStock);
					}
				}
			}
			sp.setPipe_num(pipenum);
			storagePartitionService.saveStoragePartition(sp);
			json.put("status", "1");
			out.print(json.toString());
		}
		catch(Exception e)
		{
			json.put("status", "0");
			out.print(json.toString());
		}
	}
	
	@RequestMapping(value = "printStock", method = RequestMethod.POST)
	public void printStock(HttpServletRequest request,
			HttpServletResponse response) {
		String code = request.getParameter("code");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			if (code == null) {
				out.print("{\"status\":\"0\"}");
				return;
			}
			List<PipeStock> pipeStocks = storageService.getPipeStock(code);
			if(pipeStocks.isEmpty())
			{
				out.print("{\"status\":\"0\"}");
				return;
			}
			JSONObject json = new JSONObject();
			json.put("status", "1");
			json.put("content", pipeStocks);
			out.print(json.toString());
		} catch (Exception e) {
			out.print("{\"status\":\"0\"}");
			
		}
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadStorage")
	public Storage getStorage(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return storageService.getStorage(id);
		}
		return null;
	}
}